package cn.chanel.mall.controller;

import cn.chanel.mall.constant.CookieName;
import cn.chanel.mall.service.CartService;
import cn.chanel.mall.service.OrderService;
import cn.chanel.mall.service.UserService;
import cn.chanel.mall.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/order")
public class OrderController {
    @Resource
    private UserService userService;

    @Resource
    private OrderService orderService;

    @GetMapping("create")
    public ModelAndView createOrder(
            @RequestParam String cartId,
            @CookieValue(name = CookieName.USER_LOGIN, required = false) String user,
            Map<String, Object> map){
        if(StringUtils.hasText(user)){
            map.put("userInfo", userService.findUserById(user));
            orderService.createOrder(cartId);
            return new ModelAndView("redirect:/order/list", map);
        }else {
            // 未登录就去登录
            return new ModelAndView("redirect:/user/login?failed=false");
        }
    }

    @GetMapping("list")
    public ModelAndView orderList(@CookieValue(name = CookieName.USER_LOGIN, required = false) String user,
                                  Map<String, Object> map){
        if(StringUtils.hasText(user)){
            map.put("userInfo", userService.findUserById(user));
            List<OrderVO> orderVOList = orderService.getAllOrderByUser(user);
            map.put("orderVOList", orderVOList);
            return new ModelAndView("order", map);
        }else {
            // 未登录就去登录
            return new ModelAndView("redirect:/user/login?failed=false");
        }
    }
}
